package Services;

import Entity.Appointment;
import Entity.MedicalRecord;
import Entity.Vaccine;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;

public class MedicalRecordService{

    public MedicalRecordService(EntityManagerFactory emf) {
        this.emf = emf;
        vaccineService = new VaccineService (emf);
        appointmentService = new AppointmentService(emf);
    }
    private EntityManagerFactory emf = null;
    AppointmentService appointmentService = null;
    VaccineService vaccineService= null;
    
    private EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(MedicalRecord record) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(record);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(MedicalRecord record) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            record = em.merge(record);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                long id = record.getId();
                if (findMedicalRecord(id) == null) {
                    throw new NonexistentEntityException("The record whit id" + id + "no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {

        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            MedicalRecord record;
            try {
               record = em.getReference(MedicalRecord.class, id);
               record.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The record whit id" + id + "no longer exists.", enfe);
            }
            em.remove(record);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<MedicalRecord> findMedicalRecordEntities() {
        return findMedicalRecordEntities(true, -1, -1);
    }

    public List<MedicalRecord> findMedicalRecordEntities(int maxResults, int firstResult) {
        return findMedicalRecordEntities(false, maxResults, firstResult);
    }

    private List<MedicalRecord> findMedicalRecordEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(MedicalRecord.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            for (int i = 0; i < q.getResultList().size(); i++) {
                MedicalRecord record = (MedicalRecord) q.getResultList().get(i);
                long recordId = record.getId();
                Query query = em.createNativeQuery("Select id from vaccine where ID=" + recordId);
                record.setVaccinesList(findVaccines(query));
                record.setAppointment(findAppointments(query));
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    
    @SuppressWarnings("empty-statement")
    public MedicalRecord findMedicalRecord(Long id) {
        EntityManager em = getEntityManager();
        try {
            MedicalRecord record = em.find(MedicalRecord.class, id);
            long recordId = record.getId();
            Query query = em.createNativeQuery ("select id from medicalrecord where ID =" + recordId);
            record.setVaccinesList(findVaccines(query));
            record.setAppointment(findAppointments(query));
            return record;
        } finally {
            em.close();
        }
    }
    private List<Vaccine> findVaccines(Query query) {
        List<Vaccine> vaccines = new ArrayList<>();
        for (int j = 0; j < query.getResultList().size(); j++)  {
            Long vaccineId = (Long) query.getResultList().get(j);
            vaccines.add((Vaccine) vaccineService.findVaccine(vaccineId));
        }
        return vaccines;
    }
    
    private List<Appointment> findAppointments(Query query) {
        List<Appointment> appointments = new ArrayList<>();
        for (int j = 0; j < query.getResultList().size(); j++)  {
            Long appointmentId = (Long) query.getResultList().get(j);
            appointments.add((Appointment) appointmentService.findAppointment(appointmentId));
        }
        return appointments;
    }
    
    public int getMedicalRecordCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<MedicalRecord> rt = cq.from(MedicalRecord.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
